﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

public class LoginAuthorizeFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 排除登录相关的Action
        var controllerName = context.RouteData.Values["controller"]?.ToString();
        var actionName = context.RouteData.Values["action"]?.ToString();
        if (controllerName == "Login" && (actionName == "Login" || actionName == "CaptchaImage" || actionName == "Logout"))
        {
            return;
        }

        // 校验Session
        var loginUserName = context.HttpContext.Session.GetString("LoginUserName");
        if (string.IsNullOrEmpty(loginUserName))
        {
            context.Result = new RedirectToActionResult("Login", "Login", null);
            return;
        }

        // 对受保护页面添加缓存控制（关键：防止浏览器缓存）
        context.HttpContext.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
        context.HttpContext.Response.Headers["Pragma"] = "no-cache";
        context.HttpContext.Response.Headers["Expires"] = "0";
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 此处可添加执行后的逻辑（如日志），暂无需处理
    }
}